package com.yycx.module.bus.provider.service.hy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaDelete;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.ConvertUtils;
import com.yycx.common.utils.DateUtils;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.service.BaseUserService;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.entity.hy.BusHyorderReturn;
import com.yycx.module.bus.client.entity.hy.BusPaymentOrder;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.entity.hy.HyOrderDetail;
import com.yycx.module.bus.client.enums.HySaleTypeEnum;
import com.yycx.module.bus.client.enums.SaleTypeEnum;
import com.yycx.module.bus.client.enums.SendTypeEnum;
import com.yycx.module.bus.client.vo.OrderCustomReturn;
import com.yycx.module.bus.provider.handler.haiying.BusinessUtils;
import com.yycx.module.bus.provider.handler.haiying.HyOrderUtils;
import com.yycx.module.bus.provider.mapper.hy.HyOrderDetailMapper;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.BusHyorderInoviceDetailsService;
import com.yycx.module.bus.provider.service.hy.BusPaymentOrderService;
import com.yycx.module.bus.provider.service.hy.HyOrderDetailService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import com.yycx.module.system.client.entity.SysBank;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.client.entity.SysPrintDesigner;
import com.yycx.module.system.provider.service.SysBankService;
import com.yycx.module.system.provider.service.SysCompanyService;
import com.yycx.module.system.provider.service.SysPrintDesignerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 海鹰销售单接口实现类
 *
 * @author flyme
 * @date 2020-08-17
 */
@Service
@DSTransactional
public class HyOrderDetailServiceImpl extends BaseServiceImpl<HyOrderDetailMapper, HyOrderDetail> implements HyOrderDetailService {


    @Autowired
    private HyOrderService hyOrderService;

    @Autowired
    private HyOrderUtils hyOrderUtils;

    @Resource
    private BusSalemanService saleManService;

    @Autowired
    private SysBankService bankService;

    @Resource
    private BusinessUtils businessUtils;

    @Resource
    private SysCompanyService companyService;

    @Resource
    private BaseUserService baseUserService;
    @Autowired
    private SysPrintDesignerService sysPrintDesignerService;

    @Resource
    private BusCustomService customService;

    @Autowired
    @Lazy
    private BusPaymentOrderService paymentOrderService;


    @Resource
    private BaseUserService userService;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody<EntityMap> beforePageList(CriteriaQuery<HyOrderDetail> cq, HyOrderDetail bod, EntityMap requestMap) {
        String orderId = bod.getOrderId();
        cq.select(HyOrderDetail.class, "*");
        cq.eq(FlymeUtils.isNotEmpty(orderId), "ho.orderId", orderId);
        cq.eq(HyOrderDetail.class, "orderDetailsState", CommonConstants.ENABLED);
        cq.createJoin(HyOrder.class);
        return ResultBody.ok();
    }

    @Override
    public ResultBody beforeListEntityMap(CriteriaQuery<HyOrderDetail> cq, HyOrderDetail hyOrderDetail, EntityMap requestMap) {
        cq.eq(HyOrderDetail.class, "orderId");
        cq.createJoin(HyOrder.class);
        return super.beforeListEntityMap(cq, hyOrderDetail, requestMap);
    }


    @Override
    public Boolean updateCustomBond(BusPayment payment) {
        HyOrderDetail orderDetails = new HyOrderDetail();
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql("customBondTakeAmount=customBond");
        //更新订单回款状态为已认款
        cu.set(true, "customBondState", CommonConstants.INT_1);
        cu.set(true, "customBondBankName", payment.getBankName());
        cu.set(true, "customBondBankNo", payment.getBankNo());
        cu.set(true, "customBondDate", DateUtils.formatDate(payment.getAmountDate(), "yyyy-MM-dd"));
        cu.eq(true, "orderId", payment.getOrderId());
        return update(cu);
    }


    @Override
    public Boolean updateDeptSettleApplyId(Long paymentId, String settleIds) {
        HyOrderDetail orderDetails = new HyOrderDetail();
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "deptSettleApplyId", paymentId);
        cu.in(true, "orderDetailsId", settleIds.split(","));
        return update(cu);
    }

    @Override
    public Boolean updateRefundBondId(Long paymentId, String selectIds) {
        HyOrderDetail orderDetails = new HyOrderDetail();
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "refundBondId", paymentId);
        cu.in(true, "orderDetailsId", selectIds.split(","));
        return update(cu);
    }


    @Override
    public ResultBody chaiFen(OrderCustomReturn bocr) {
        Long orderDetailsId = bocr.getOrderDetailsId();
        HyOrderDetail orderDetails = getById(orderDetailsId);
        ApiAssert.isNotEmpty("orderDetails不能为空", orderDetails);
        //父明细ID
        String parentId = orderDetails.getParentId();
        String orderId = orderDetails.getOrderId();
        HyOrder busOrder = hyOrderService.getById(orderId);
        chaiFenByParent(bocr, orderDetails);
        return ResultBody.ok();
    }

    @Override
    public HyOrderDetail addDiscountDetails(HyOrderDetail orderDetails, HyOrder hyOrder, BigDecimal saleAmount) {
        HyOrderDetail discountDetails = new HyOrderDetail();
        ApiAssert.isNotEmpty("orderDetails不能为空", orderDetails);
        //票折金额
        BigDecimal discountSaleAmount = saleAmount.multiply(new BigDecimal("-1"));
        String parentId = orderDetails.getParentId();
        //拷贝属性
        BeanUtil.copyProperties(orderDetails, discountDetails);
        //设置为票折类型
        discountDetails.setSaleType(HySaleTypeEnum.Pz.getCode());
        if (FlymeUtils.isNotEmpty(parentId)) {
            discountDetails.setParentId(parentId);
        } else {
            discountDetails.setParentId(orderDetails.getOrderDetailsId());
        }
        //渠道商结算费率
        BigDecimal settleRate = orderDetails.getSettleRate();
        //票折公式
        if (FlymeUtils.isNotEmpty(settleRate)) {
            discountDetails.setSettleFormulaContent("票折金额*(1-渠道商标准);");

        }
        discountDetails.setSaleAmount(discountSaleAmount);
        hyOrderUtils.computeFee(hyOrder, discountDetails, false, true);

        discountDetails.setOrderDetailsId(IdWorker.getIdStr());
        discountDetails.setCostAmount(new BigDecimal("0"));
        discountDetails.setCustomBond(new BigDecimal("0"));
        discountDetails.setSalePrice(new BigDecimal("0"));
        discountDetails.setSaleNum(new BigDecimal("0"));
        discountDetails.setSettlePrice(new BigDecimal("0"));
        discountDetails.setDeptPrice(new BigDecimal("0"));
        discountDetails.setSettlePriceC(new BigDecimal("0"));
        discountDetails.setSettlePriceD(new BigDecimal("0"));
        discountDetails.setSettlePriceE(new BigDecimal("0"));
        discountDetails.setDeptSettleAmount(new BigDecimal("0"));
        discountDetails.setSettleSendAmount(new BigDecimal("0"));
        discountDetails.setCostPrice(new BigDecimal("0"));
        discountDetails.setSurplusNum(new BigDecimal("0"));
        discountDetails.setCustomFloorAmount(new BigDecimal("0"));
        discountDetails.setCustomGapUpAmount(new BigDecimal("0"));
        //保证金票折时金额不取值
        discountDetails.setCustomBondTakeAmount(new BigDecimal("0"));
        saveOrUpdate(discountDetails);

        return discountDetails;
    }

    @Override
    public ResultBody addDiscountDetails(String orderDetailsId, BigDecimal saleAmount) {
        HyOrderDetail orderDetails = getById(orderDetailsId);
        HyOrder hyOrder = hyOrderService.getById(orderDetails.getOrderId());
        addDiscountDetails(orderDetails, hyOrder, saleAmount);
        String orderId = orderDetails.getOrderId();
        List<BusPaymentOrder> paymentOrder = paymentOrderService.selectByOrderId(orderId);
        if (FlymeUtils.isNotEmpty(paymentOrder)) {
            for (BusPaymentOrder busPaymentOrder : paymentOrder) {
                BigDecimal amount = busPaymentOrder.getTakeAmount();
                if (FlymeUtils.ge(amount, saleAmount)) {
                    BusPaymentOrder busPaymentOrder1 = new BusPaymentOrder();
                    BeanUtils.copyProperties(busPaymentOrder, busPaymentOrder1);
                    busPaymentOrder1.setUseAmount(saleAmount.multiply(new BigDecimal("-1")));
                    busPaymentOrder1.setPaymentOrderId(IdWorker.getId());
                    paymentOrderService.save(busPaymentOrder1);
                    break;
                }
            }
        }
        return ResultBody.msg("票折成功");
    }

    @Override
    public ResultBody cancelChaiFen(String orderDetailsId) {
        HyOrderDetail orderDetails = getById(orderDetailsId);
        if (FlymeUtils.isNotEmpty(orderDetails)) {
            HyOrder hyOrder = hyOrderService.getById(orderDetails.getOrderId());
            String parentId = orderDetails.getParentId();
            BigDecimal saleNum = orderDetails.getSaleNum();
            if (FlymeUtils.isNotEmpty(parentId)) {
                HyOrderDetail parentOrderDetails = getById(parentId);
                BigDecimal parentSaleNum = parentOrderDetails.getSaleNum();
                BigDecimal newSaleNum = saleNum.add(parentSaleNum);
                parentOrderDetails.setSaleNum(newSaleNum);
                hyOrderUtils.computeFee(hyOrder, parentOrderDetails, false, false);
                saveOrUpdate(parentOrderDetails);
                removeById(orderDetailsId);
            }
        }
        return ResultBody.ok();
    }

    /**
     * 拆分订单
     *
     * @param bocr
     * @param orderDetails
     */
    private void chaiFenByParent(OrderCustomReturn bocr, HyOrderDetail orderDetails) {
        Long orderDetailsId = bocr.getOrderDetailsId();
        ApiAssert.isNotEmpty("orderDetails不能为空", orderDetails);
        String orderId = orderDetails.getOrderId();
        HyOrder busOrder = hyOrderService.getById(orderId);
        BigDecimal salePrice = orderDetails.getSalePrice();
        //销售数量
        BigDecimal totalSaleNum = orderDetails.getSaleNum();
        //销售金额
        BigDecimal totalSaleAmount = orderDetails.getSaleAmount();
        //父明细ID
        String parentId = orderDetails.getParentId();
        //拆分数量
        BigDecimal chaiFenNum = FlymeUtils.getBigDecimal(bocr.getReturnNum(), "0");
        //拆分金额
        BigDecimal chaiFenAmount = FlymeUtils.getBigDecimal(bocr.getReturnAmount(), "0");
        //回款方式1按数量 2按金额
        Integer returnType = bocr.getReturnType();
        //按金额
        if (returnType.equals(2)) {
            //计算回款比例
            BigDecimal ratio = chaiFenAmount.divide(totalSaleAmount, 3, BigDecimal.ROUND_HALF_UP);
            //计算回款数量
            chaiFenNum = totalSaleNum.multiply(ratio).setScale(3, BigDecimal.ROUND_HALF_UP);
        }

        //拆出新明细
        HyOrderDetail newOrderDetails = getOrderDetails(orderDetails, chaiFenNum, true);
        hyOrderUtils.computeFee(busOrder, newOrderDetails, false, false);
        //保存新明细
        saveOrUpdate(newOrderDetails);
        //剩余数量
        BigDecimal surplusNum = totalSaleNum.subtract(chaiFenNum);
        //修改当前明细
        HyOrderDetail oldOrderDetails = getOrderDetails(orderDetails, surplusNum, false);
        hyOrderUtils.computeFee(busOrder, oldOrderDetails, false, false);
        //更新之前明细
        saveOrUpdate(oldOrderDetails);
    }

    /**
     * 根据父明细拆出新明细
     *
     * @param orderDetails
     * @param returnNum
     * @param chiaFenAmont
     * @param ratio
     * @return
     */
    private HyOrderDetail getOrderDetails(HyOrderDetail orderDetails, BigDecimal saleNum, Boolean isNew) {
        HyOrderDetail newOrderDetails = new HyOrderDetail();
        BeanUtil.copyProperties(orderDetails, newOrderDetails);
        if (isNew) {
            if (FlymeUtils.isNotEmpty(orderDetails.getParentId())) {
                newOrderDetails.setParentId(orderDetails.getParentId());
            } else {
                newOrderDetails.setParentId(orderDetails.getOrderDetailsId());
            }
            newOrderDetails.setOrderDetailsId(IdWorker.getIdStr());
        }
        newOrderDetails.setSaleNum(saleNum);
        /*newOrderDetails.setSaleAmount(chiaFenAmont);
        newOrderDetails.setSettleAmount(getAmount(orderDetails.getSettleAmount(), ratio));
        newOrderDetails.setCostAmount(getAmount(orderDetails.getCostAmount(), ratio));
        newOrderDetails.setCustomGapUpTaxesAmount(getAmount(orderDetails.getCustomGapUpTaxesAmount(), ratio));
        newOrderDetails.setCustomSettleGapUpAmount(getAmount(orderDetails.getCustomSettleGapUpAmount(), ratio));
        newOrderDetails.setProfitAmount(getAmount(orderDetails.getProfitAmount(), ratio));
        newOrderDetails.setCustomFloorAmount(getAmount(orderDetails.getCustomFloorAmount(), ratio));
        newOrderDetails.setSettleSendAmount(getAmount(orderDetails.getSettleSendAmount(), ratio));
        newOrderDetails.setCustomGapUpAmount(getAmount(orderDetails.getCustomGapUpAmount(), ratio));
        newOrderDetails.setCustomYsk(getAmount(orderDetails.getCustomYsk(), ratio));
        newOrderDetails.setRefundAmount(getAmount(orderDetails.getRefundAmount(), ratio));*/
        return newOrderDetails;
    }

    private BigDecimal getAmount(BigDecimal amount, BigDecimal radio) {
        if (FlymeUtils.isNotEmpty(amount)) {
            return amount.multiply(radio).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        return new BigDecimal("0");
    }


    /**
     * 根据订单ID删除订单明细
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean delByOrderId(Serializable orderId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq(true, "orderId", orderId);
        return remove(cd);
    }

    @Override
    public Boolean deleteById(Serializable orderDetailsId) {
        HyOrderDetail orderDetails = getById(orderDetailsId);
        if (FlymeUtils.isNotEmpty(orderDetails)) {
            removeById(orderDetailsId);
        }
        return true;
    }


    /**
     * 补货申请
     *
     * @param orderDetailsId 原订单明细ID
     * @param saleType       类型(2:退货，3补货)
     * @param saleNum        数量
     * @param backDate       退货日期
     */
    @Override
    public ResultBody replenishOrder(Long orderDetailsId, String saleType, BigDecimal saleNum, String backDateStr) {
        Date backDate = DateUtils.parseDate(backDateStr);
        //查询原订单明细
        HyOrderDetail orderDetails = getById(orderDetailsId);
        HyOrder order = null;
        //订单ID
        String orderId = null;
        if (saleType.equals(SaleTypeEnum.Bh.getCode())) {
            //补货用原订单ID
            HyOrderDetail details = getById(orderDetails.getParentId());
            //查询原来订单
            order = hyOrderService.getById(details.getOrderId());
            orderId = order.getOrderId();
        } else {
            //订单ID
            orderId = orderDetails.getOrderId();
            //查询原来订单
            order = hyOrderService.getById(orderId);
        }
        HyOrder backOrder = new HyOrder();
        BeanUtils.copyProperties(order, backOrder);
        backOrder.setProcessInstanceId(null);
        backOrder.setOrderId(IdWorker.getIdStr());
        backOrder.setOrderState(CommonConstants.INT_0);
        backOrder.setTakeDate(order.getTakeDate());
        backOrder.setParentId(orderId);
        backOrder.setTakeDate(null);
        backOrder.setBankId(null);
        backOrder.setTakeAmount(new BigDecimal("0"));
        backOrder.setCreateTime(DateUtils.getNowDateTime());
        //退货日期
        backOrder.setSendDate(backDate);
        if (saleType.equals(HySaleTypeEnum.CHC.getCode())) {
            //退货取负值
            saleNum = saleNum.multiply(new BigDecimal("-1"));
            backOrder.setOrderType(HySaleTypeEnum.CHC.getCode());
            backOrder.setOrderNo("T" + order.getOrderNo());
        } else {
            backOrder.setOrderNo("B" + order.getOrderNo());
            backOrder.setOrderType(HySaleTypeEnum.Bh.getCode());
        }
        orderDetails.setOrderId(backOrder.getOrderId());
        //addBackOrderDetails(order, orderDetails, saleNum, null, true);
        //添加退货单
        hyOrderService.save(backOrder);
        return ResultBody.ok();
    }

    /**
     * 订单核算
     *
     * @param params
     * @return
     */
    @Override
    public ResultBody calculate(Map params) {
        HyOrderDetail orderDetails = BeanUtil.toBean(params, HyOrderDetail.class);
        //订单明细ID
        String orderDetailsId = orderDetails.getOrderDetailsId();
        //查询订单明细
        HyOrderDetail oldOrderDetails = getById(orderDetailsId);
        //订单ID
        String orderId = oldOrderDetails.getOrderId();
        //查询订单
        HyOrder oldOrder = hyOrderService.getById(orderId);
        //使用前端传递的属性覆盖
        BeanUtil.copyProperties(orderDetails, oldOrderDetails, CopyOptions.create().ignoreNullValue());
        //查询业务员
        BusSaleman saleMan = saleManService.getById(oldOrder.getSaleManId());
        //重置订单相关提成人员
        oldOrder.setSaleManIdF(null);
        oldOrder.setSaleManIdD(null);
        oldOrder.setSaleManIdC(null);
        oldOrder.setSaleManIdE(null);
        oldOrder.setRebateState(0);
        //设置订单相关提成人员
        hyOrderUtils.setSaleManInfo(oldOrder, saleMan);
        //订单类型
        String saleType=oldOrderDetails.getSaleType();
        //是否票折订单
        Boolean isPz=HySaleTypeEnum.Pz.getCode().equals(saleType);
        //重新计算费用
        hyOrderUtils.computeFee(oldOrder, oldOrderDetails, true, isPz);
        //更新订单
        hyOrderService.updateById(oldOrder);
        if(isPz){
            oldOrderDetails.setCustomGapUpTaxesAmount(new BigDecimal("0"));
            oldOrderDetails.setCostAmount(new BigDecimal("0"));
            oldOrderDetails.setCustomBond(new BigDecimal("0"));
            //oldOrderDetails.setSalePrice(new BigDecimal("0"));
            //oldOrderDetails.setSaleNum(new BigDecimal("0"));
            oldOrderDetails.setSettlePrice(new BigDecimal("0"));
            //oldOrderDetails.setDeptPrice(new BigDecimal("0"));
            oldOrderDetails.setSettlePriceC(new BigDecimal("0"));
            oldOrderDetails.setSettlePriceD(new BigDecimal("0"));
            oldOrderDetails.setSettlePriceE(new BigDecimal("0"));
            oldOrderDetails.setSettleSendAmount(new BigDecimal("0"));
            oldOrderDetails.setCostPrice(new BigDecimal("0"));
            oldOrderDetails.setSurplusNum(new BigDecimal("0"));
            oldOrderDetails.setCustomFloorAmount(new BigDecimal("0"));
            oldOrderDetails.setCustomGapUpAmount(new BigDecimal("0"));
            //保证金票折时金额不取值
            oldOrderDetails.setCustomBondTakeAmount(new BigDecimal("0"));
        }
        //更新为已核算
        oldOrderDetails.setCalculateState(1);
        //更新订单明细
        updateById(oldOrderDetails);
        return ResultBody.msg("核算成功!");
    }

    @Override
    public List<HyOrderDetail> selectByParentId(Long parentId, HySaleTypeEnum saleType) {
        CriteriaQuery cq = new CriteriaQuery(BusOrderDetails.class);
        cq.eq(true, "parentId", parentId);
        cq.eq(true, "saleType", saleType.getCode());
        cq.eq(true, "orderDetailsState", CommonConstants.ENABLED);
        return list(cq);
    }

    @Override
    public List<HyOrderDetail> selectByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.eq(true, "orderId", orderId);
        cq.orderByAsc("createTime", "orderDetailsId");
        return list(cq);
    }


    @Override
    public List<HyOrderDetail> selectInsertToReturnList(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.eq(true, "orderId", orderId);
        cq.orderByDesc("saleAmount");
        return list(cq);
    }

    @Override
    public List<EntityMap> selectByOrderId(String orderId, HySaleTypeEnum saleType) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "orderDetailsId", "orderId", "parentId", "drugLotNo", "drugNo", "drugsName", "drugsSpec", "sendDate", "saleNum", "salePrice", "saleAmount", "costPrice", "costAmount", "storeCode", "drugJs", "generationDate", "expirationDate", "reason");
        cq.eq(true, "orderId", orderId);
        cq.eq(true, "saleType", saleType.getCode());
        cq.orderByAsc("createTime", "orderDetailsId");
        return selectEntityMap(cq);
    }

    @Override
    public List<EntityMap> selectMapListByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "orderDetailsId", "orderId", "parentId", "drugLotNo", "drugNo", "drugsName", "drugsSpec", "sendDate", "saleNum", "salePrice", "saleAmount", "costPrice", "costAmount", "storeCode", "drugJs", "generationDate", "expirationDate", "reason", "producersName");
        cq.eq(true, "orderId", orderId);
        return selectEntityMap(cq);
    }

    @Override
    public List<HyOrderDetail> selectAllFieldByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "*");
        cq.eq(true, "orderId", orderId);
        return list(cq);
    }


    /**
     * 导出专用
     *
     * @param orderId
     * @return
     */
    @Override
    public List<EntityMap> selectMapByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "orderDetailsId", "drugsName", "drugsSpec", "drugJr", "producersName", "sendDate", "format(saleNum,0) saleNum", "format(salePrice,2) salePrice", "format(saleAmount,2) saleAmount");
        cq.eq(true, "orderId", orderId);
        cq.orderByAsc("createTime", "orderDetailsId");
        return selectEntityMap(cq);
    }

    /**
     * 添加订单回显明细
     *
     * @param orderId
     * @return
     */
    @Override
    public List<EntityMap> selectOrderDetailsByOrderId(String orderId, HySaleTypeEnum hySaleTypeEnum) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "orderDetailsId", "drugsId", "drugNo", "policyDrugId", "discountPrice", "producersName", "drugsName", "drugsSpec", "drugJr", "drugLotId", "drugLotNo", "storeName", "storeCode", "salePrice", "saleAmount", "costPrice", "saleNum", "surplusNum", "expirationDate", "generationDate");
        cq.eq(true, "orderId", orderId);
        cq.eq(true, "saleType", hySaleTypeEnum.getCode());
        cq.orderByAsc("createTime");
        return selectEntityMap(cq);
    }

    /**
     * 查询已用资信额度
     *
     * @param saleManId
     * @return
     */
    @Override
    public BigDecimal totalReputationAmount(Long saleManId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("sum(saleAmount) saleAmount");
        //全额资信发货
        cq.eq(HyOrder.class, "sendType", SendTypeEnum.QZ.getCode());
        //未返款或者返款未审批
        cq.eq("bhd.customReturnState", 0);
        cq.eq(true, "bhd.saleManId", saleManId);
        cq.createJoin(HyOrder.class);
        EntityMap map = findOne(cq);
        if (FlymeUtils.isNotEmpty(map)) {
            return map.getBigDecimal("saleAmount");
        } else {
            return new BigDecimal("0");
        }
    }

    @Override
    public EntityMap totalSettleAmount(String settleIds, Integer settleType) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        if (settleType.equals(1)) {
            cq.select("sum(settleAmount) settleAmount,deptId");
        }
        if (settleType.equals(2)) {
            cq.select("sum(settleAmountD) settleAmount,deptId");
        }
        if (settleType.equals(3)) {
            cq.select("sum(settleAmountC) settleAmount,deptId");
        }
        if (settleType.equals(4)) {
            cq.select("sum(settleAmountE) settleAmount,deptId");
        }
        cq.in(true, "orderDetailsId", settleIds.split(","));
        return findOne(cq);
    }


    @Override
    public BigDecimal totalSaleAmount(String settleIds) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("sum(saleAmount)");
        cq.in(true, "orderDetailsId", settleIds.split(","));
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        return FlymeUtils.getBigDecimal(amount, new BigDecimal("0"));
    }


    @Override
    public EntityMap totalDeptSettleInfo(String settleIds) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("count(DISTINCT drugType) count,sum(deptSettleAmount) deptSettleAmount,drugType");
        cq.in(true, "orderDetailsId", settleIds.split(","));
        cq.isNull("deptSettleApplyId");
        return findOne(cq);
    }

    @Override
    public EntityMap totalRefundBondInfo(String selectIds) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("count(DISTINCT drugType) count,count(DISTINCT saleManId) saleManIdCount,sum(customBondTakeAmount) customBondTakeAmount,drugType,saleManId,deptId");
        cq.in(true, "orderDetailsId", selectIds.split(","));
        cq.isNull("deptSettleApplyId");
        return findOne(cq);
    }


    /**
     * 清空结算申请信息
     */
    @Override
    public Boolean clearDeptSettleApplyId(Serializable settleApplyId) {
        if (FlymeUtils.allNotNull(settleApplyId)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.set(true, "deptSettleApplyId", null);
            cu.eq(true, "deptSettleApplyId", settleApplyId);
            update(cu);
        }
        return true;
    }

    /**
     * 清空退保证金请信息
     */
    @Override
    public Boolean clearRefundBondId(Serializable refundBondId) {
        if (FlymeUtils.allNotNull(refundBondId)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.set(true, "refundBondId", null);
            cu.eq(true, "refundBondId", refundBondId);
            update(cu);
        }
        return true;
    }


    @Override
    public Boolean updateDeptSettleAmount(BusPayment payment) {
        Integer settleType = payment.getSettleType();
        CriteriaUpdate cu = new CriteriaUpdate();
        //部门结算
        cu.setSql("deptSettlePayAmount=deptSettleAmount");
        cu.set(true, "deptSettlePayDate", DateUtils.formatDate(payment.getPayDate(), "yyyy-MM-dd"));
        cu.set(true, "deptSettleState", CommonConstants.INT_1);
        cu.eq(true, "deptSettleInvoiceId", payment.getPaymentId());
        return update(cu);
    }

    @Override
    public Boolean updateRefundBond(BusPayment payment) {
        Integer settleType = payment.getSettleType();
        CriteriaUpdate cu = new CriteriaUpdate();
        Long payBankId = payment.getPayBankId();
        SysBank bank = bankService.getById(payBankId);
        //部门结算
        cu.setSql("customBondRetAmount=customBondTakeAmount");
        cu.set(true, "customBondRetDate", DateUtils.formatDate(payment.getPayDate(), "yyyy-MM-dd"));
        cu.set(true, "customBondState", CommonConstants.INT_1);
        cu.set(true, "customBondRetBankNo", bank.getBankNo());
        cu.set(true, "customBondRetBankName", bank.getBankName());
        cu.eq(true, "refundBondId", payment.getPaymentId());
        return update(cu);
    }


    @Override
    public List<EntityMap> totalDrugLotNum(String orderId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("sum(saleNum) saleNum,drugLotId,drugNo");
        cq.eq(true, "orderId", orderId);
        cq.groupBy("drugLotId");
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody reportYearHead(Map params) {
        Long companyId = MapUtil.getLong(params, "companyId");
        int year = DateUtil.thisYear();
        int month = DateUtil.thisMonth() + 1;

        List<Map<Object, Object>> resList = new ArrayList<>();

        for (int i = 0; i < month; i++) {
            int finalI = i;
            HashMap dataIndex = new HashMap<Object, Object>() {{
                put("dataIndex", year + "-" + (finalI + 1));
                put("key", year + "-" + (finalI + 1));
                put("title", (finalI + 1) + "月");
                put("width", 100);
            }};
            resList.add(dataIndex);
        }


        return ResultBody.ok(resList);
    }

    @Override
    public ResultBody reportList(Map params) {
        return null;
    }

    @Override
    public ResultBody reportYearList(Map params) {
        Long companyId = MapUtil.getLong(params, "companyId");
        int year = DateUtil.thisYear();
        int month = DateUtil.thisMonth() + 1;


        List<Map<Object, Object>> resList = new ArrayList<>();

        CriteriaQuery<HyOrderDetail> currentCq = new CriteriaQuery(HyOrderDetail.class);
        currentCq.addSelect("bhd.deptId, bhd.companyId,bhd.saleManId,saleAmount,sendDate,sendYear,sendMonth,sendDay");
        currentCq.addSelect("dept.deptName");
        currentCq.addSelect("saleman.saleManName");
        currentCq.createJoin(BusDept.class);
        currentCq.createJoin(BusSaleman.class);
        currentCq.eq("sendYear", year);
        currentCq.le("sendMonth", month);
        currentCq.eq("bhd.companyId", companyId);
        List<EntityMap> currentList = selectEntityMap(currentCq);


        CriteriaQuery<HyOrderDetail> lastCq = new CriteriaQuery(HyOrderDetail.class);
        lastCq.addSelect("bhd.deptId, bhd.companyId,bhd.saleManId,saleAmount,sendDate,sendYear,sendMonth,sendDay");
        lastCq.addSelect("dept.deptName");
        lastCq.addSelect("saleman.saleManName");
        lastCq.createJoin(BusDept.class);
        lastCq.createJoin(BusSaleman.class);
        lastCq.eq("sendYear", year - 1);
        lastCq.eq("bhd.companyId", companyId);
        List<EntityMap> lastList = selectEntityMap(lastCq);

        Map<Long, List<Map<Object, Object>>> lastResMap = new HashMap<>();
        if (CollUtil.isNotEmpty(lastList)) {
            Map<Integer, Double> lastMap = new HashMap();
            for (int i = 0; i < 12; i++) {
                lastMap.put(i + 1, 0D);
            }
            Map<Long, List<EntityMap>> lastDeptMap = lastList.stream().collect(Collectors.groupingBy(a -> a.getLong("deptId")));
            Set<Long> deptIds = lastDeptMap.keySet();
            for (Long deptId : deptIds) {
                List<Map<Object, Object>> lastResList = new ArrayList<>();
                Map<Object, Object> res = new HashMap<>();
                List<EntityMap> entityMaps = lastDeptMap.get(deptId);
                Map<Integer, List<EntityMap>> monthMap = entityMaps.stream().collect(Collectors.groupingBy(a -> a.getInt("sendMonth")));
                for (Integer o : lastMap.keySet()) {
                    List<EntityMap> entityMaps1 = monthMap.get(o);
                    if (ObjUtil.isNotNull(entityMaps1) && CollUtil.isNotEmpty(entityMaps1)) {
                        res.put((year - 1) + "-" + o, entityMaps1.stream().mapToDouble(a -> a.getBigDecimal("saleAmount").doubleValue()).sum());
                    } else {
                        res.put((year - 1) + "-" + o, 0);
                    }
                }
                res.put("deptId", deptId);
                res.put("lastTotal", entityMaps.stream().mapToDouble(a -> a.getBigDecimal("saleAmount").doubleValue()).sum());
                lastResList.add(res);
                lastResMap.put(entityMaps.get(0).get("deptId"), lastResList);
            }

        }
        if (CollUtil.isNotEmpty(currentList)) {


            Map<Long, List<EntityMap>> deptMap = currentList.stream().collect(Collectors.groupingBy(a -> a.getLong("deptId")));
            Set<Long> deptIds = deptMap.keySet();
            Map<Integer, Double> currentMap = new HashMap();

            for (int i = 0; i < month; i++) {
                currentMap.put(i + 1, 0D);
            }
            for (Long deptId : deptIds) {
                Map<Object, Object> res = new HashMap<>();
                List<EntityMap> entityMaps = deptMap.get(deptId);
                Map<Integer, List<EntityMap>> monthMap = entityMaps.stream().collect(Collectors.groupingBy(a -> a.getInt("sendMonth")));
                for (Integer o : currentMap.keySet()) {
                    List<EntityMap> entityMaps1 = monthMap.get(o);
                    if (ObjUtil.isNotNull(entityMaps1) && CollUtil.isNotEmpty(entityMaps1)) {
                        res.put((year) + "-" + o, entityMaps1.stream().mapToDouble(a -> a.getBigDecimal("saleAmount").doubleValue()).sum());
                    } else {
                        res.put((year) + "-" + o, 0);
                    }
                }
                res.put("deptId", deptId);
                res.put("deptName", entityMaps.get(0).get("deptName"));
                res.put("currentTotal", entityMaps.stream().mapToDouble(a -> a.getBigDecimal("saleAmount").doubleValue()).sum());

                //环比
                res.put("qoq", MapUtil.getDouble(res, (year) + "-" + (month - 1)) > 0 ? new BigDecimal(((MapUtil.getDouble(res, (year) + "-" + month) - MapUtil.getDouble(res, (year) + "-" + (month - 1))) / MapUtil.getDouble(res, (year) + "-" + (month - 1)) * 100)).setScale(2, BigDecimal.ROUND_HALF_UP) + "%" : 0);


                if (ObjUtil.isNotNull(lastResMap.get(deptId))) {

                    List<Map<Object, Object>> maps = lastResMap.get(deptId);

                    Map<Object, Object> objectObjectMap = maps.get(0);
                    res.put("total", MapUtil.getDouble(objectObjectMap, "lastTotal") + MapUtil.getDouble(res, "currentTotal"));
                    //同比
                    res.put("yoy", 0);
                    res.putAll(objectObjectMap);

                } else {
                    for (int i = 1; i < 13; i++) {
                        res.put((year - 1) + "-" + i, 0);
                    }
                    res.put("total", MapUtil.getDouble(res, "currentTotal"));

                    res.put("lastTotal", 0);
                    //同比
                    res.put("yoy", 0);
                }
                resList.add(res);
            }

        }

        EntityMap pageModel = new EntityMap();
        pageModel.put("size", resList.size());
        pageModel.put("total", resList.size());
        pageModel.put("current", 1);
        pageModel.put("pages", resList.size());
        pageModel.put("records", resList);
        return ResultBody.ok(pageModel);
    }


    @Override
    public ResultBody reportDayHead(Map params) {

        String beginDate1 = MapUtil.getStr(params, "beginDate", "");
        String endDate1 = MapUtil.getStr(params, "endDate");

        Date beginDate = StrUtil.isNotBlank(beginDate1) ? DateUtil.parse(beginDate1, DatePattern.NORM_DATE_PATTERN) : DateUtil.beginOfWeek(DateUtil.date(), true);
        Date endDate = StrUtil.isNotBlank(endDate1) ? DateUtil.parse(endDate1, DatePattern.NORM_DATE_PATTERN) : DateUtil.endOfWeek(DateUtil.date(), true);
        long between = DateUtil.betweenDay(beginDate, endDate, true);
        List<JSONObject> resList = new ArrayList<>();
        for (int i = 0; i <= between; i++) {
            int finalI = i;
            JSONObject obj = JSONUtil.createObj();
            obj.set("title", DateUtil.format(DateUtil.offsetDay(beginDate, finalI), "M月dd日"));
            obj.set("align", "center");

            List<Map> list = new ArrayList<>();

            Map sl = new HashMap<Object, Object>() {{
                put("dataIndex", DateUtil.format(DateUtil.offsetDay(beginDate, finalI), DatePattern.NORM_DATE_PATTERN) + "sl");
                put("key", DateUtil.format(DateUtil.offsetDay(beginDate, finalI), DatePattern.NORM_DATE_PATTERN) + "sl");
                put("title", "数量");
                put("width", 100);
            }};
            Map dj = new HashMap<Object, Object>() {{
                put("dataIndex", DateUtil.format(DateUtil.offsetDay(beginDate, finalI), DatePattern.NORM_DATE_PATTERN) + "dj");
                put("key", DateUtil.format(DateUtil.offsetDay(beginDate, finalI), DatePattern.NORM_DATE_PATTERN) + "dj");
                put("title", "单价");
                put("width", 100);
            }};

            list.add(sl);
            list.add(dj);
            obj.set("children", list);
            resList.add(obj);
        }

        return ResultBody.ok(resList);
    }

    @Override
    public ResultBody reportDayList(Map params) {
        Long companyId = MapUtil.getLong(params, "companyId");
        String beginDate1 = MapUtil.getStr(params, "beginDate", "");
        String endDate1 = MapUtil.getStr(params, "endDate");

        Date beginDate = StrUtil.isNotBlank(beginDate1) ? DateUtil.parse(beginDate1, DatePattern.NORM_DATE_PATTERN) : DateUtil.beginOfWeek(DateUtil.date(), true);
        Date endDate = StrUtil.isNotBlank(endDate1) ? DateUtil.parse(endDate1, DatePattern.NORM_DATE_PATTERN) : DateUtil.endOfWeek(DateUtil.date(), true);
        long between = DateUtil.betweenDay(beginDate, endDate, true);

        List<Map<Object, Object>> resList = new ArrayList<>();

        CriteriaQuery<HyOrderDetail> currentCq = new CriteriaQuery(HyOrderDetail.class);
        currentCq.addSelect("bhd.deptId, bhd.companyId,bhd.saleManId,drugNo,drugsName,drugsSpec , surplusNum,salePrice,sendDate,sendYear,sendMonth,sendDay");
        currentCq.addSelect("dept.deptName");
        currentCq.addSelect("saleman.saleManName");
        currentCq.createJoin(BusDept.class);
        currentCq.createJoin(BusSaleman.class);
        currentCq.le("sendDate", endDate);
        currentCq.ge("sendDate", beginDate);
        currentCq.eq("bhd.companyId", companyId);
        List<EntityMap> currentList = selectEntityMap(currentCq);


        if (CollUtil.isNotEmpty(currentList)) {


            Map<String, List<EntityMap>> drugMap = currentList.stream().collect(Collectors.groupingBy(a -> a.get("drugNo").toString() + "_" + a.get("drugsSpec").toString()));
            Set<String> drugNos = drugMap.keySet();
            Map<String, Double> currentMap = new HashMap();


            for (int i = 0; i <= between; i++) {
                currentMap.put(DateUtil.format(DateUtil.offsetDay(beginDate, i), DatePattern.NORM_DATE_PATTERN), 0D);
            }
            for (String drugNo : drugNos) {
                Map<Object, Object> res = new HashMap<>();
                List<EntityMap> entityMaps = drugMap.get(drugNo);
                Map<String, List<EntityMap>> monthMap = entityMaps.stream().collect(Collectors.groupingBy(a -> a.get("sendDate").toString()));
                for (String o : currentMap.keySet()) {
                    List<EntityMap> entityMaps1 = monthMap.get(o);
                    if (ObjUtil.isNotNull(entityMaps1) && CollUtil.isNotEmpty(entityMaps1)) {
                        res.put(o + "dj", entityMaps1.stream().mapToDouble(a -> a.getBigDecimal("salePrice").doubleValue()).sum());
                        res.put(o + "sl", entityMaps1.stream().mapToDouble(a -> a.getBigDecimal("surplusNum").doubleValue()).sum());
                    } else {
                        res.put(o + "dj", 0);
                        res.put(o + "sl", 0);
                    }
                    res.put("drugsName", entityMaps.get(0).get("drugsName"));
                    res.put("drugsSpec", entityMaps.get(0).get("drugsSpec"));
                    res.put("deptName", entityMaps.get(0).get("deptName"));

                }
                res.put("priceTotal", entityMaps.stream().mapToDouble(a -> a.getBigDecimal("salePrice").doubleValue()).sum());
                res.put("numTotal", entityMaps.stream().mapToDouble(a -> a.getBigDecimal("surplusNum").doubleValue()).sum());


                resList.add(res);
            }

        }

        EntityMap pageModel = new EntityMap();
        pageModel.put("size", resList.size());
        pageModel.put("total", resList.size());
        pageModel.put("current", 1);
        pageModel.put("pages", resList.size());
        pageModel.put("records", resList);
        return ResultBody.ok(pageModel);
    }

    @Override
    public Boolean updateOutPrintTag(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "outPrintTag=outPrintTag+1");
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public ResultBody getOutOrderPrint(String orderDetailsId, Integer customCount) {
        EntityMap result = new EntityMap();
        String template = sysPrintDesignerService.getContentByDesignCode("PrintDesigner02");
        result.put("template", template);
        List<HyOrderDetail> list = getOrderDetailsList(orderDetailsId);
        List<EntityMap> dataList = new ArrayList<>();
        for (HyOrderDetail orderDetail : list) {
            String orderId = orderDetail.getOrderId();
            HyOrder order = hyOrderService.getById(orderId);
            BigDecimal drugJs = orderDetail.getPrintDrugJs();
            EntityMap map = new EntityMap();
            Long customId = order.getCustomId();
            Long companyId = order.getCompanyId();
            BusCustom custom = customService.getById(customId);
            map.put("orderDetailsId", orderDetail.getOrderDetailsId());
            SysCompany company = companyService.getById(companyId);
            //发货地址
            map.put("companyAddress", company.getCompanyAddress());
            //发货方
            map.put("companyName", company.getCompanyShortName());
            //客户名称
            map.put("customName", custom.getCustomName());
            //商品名称
            map.put("drugsName", orderDetail.getDrugsName());
            //件数
            map.put("drugJs", drugJs.setScale(2, BigDecimal.ROUND_HALF_UP));
            Integer drugJsCount = drugJs.setScale(0, BigDecimal.ROUND_UP).intValue();
            //单品件数
            map.put("drugJsCount", drugJsCount);
            //总件数
            BigDecimal totalDrugJs = new BigDecimal(customCount);
            map.put("totalDrugJs", drugJsCount + "/" + totalDrugJs.setScale(0, BigDecimal.ROUND_UP).intValue());
            //出库日期
            map.put("outDate", DateUtils.getNowDate());
            //打印日期
            map.put("printDate", DateUtils.getNowDate());

            //收货人电话
            map.put("customUserTel", order.getCustomUserTel());
            //收货人地址
            map.put("customAddress", order.getCustomAddress());
            //收货人
            map.put("customUserName", order.getCustomUserName());
            //订单编号
            map.put("outOrderNo", order.getOutOrderNo());
            map.put("barcode", "CKA" + order.getOutOrderNo());
            Long userId = OpenHelper.getUserId();
            BaseUser baseUser = baseUserService.getById(userId);
            //发货人电话
            map.put("mobile", baseUser.getMobile());
            //发货人
            map.put("outNickName", OpenHelper.getNickName());
            dataList.add(map);
        }
        result.put("dataList", dataList);
        return ResultBody.ok(result);
    }


    @Override
    public ResultBody getMergeOutOrderPrint(String orderIds) {
        EntityMap result = new EntityMap();
        String template = sysPrintDesignerService.getContentByDesignCode("PrintDesigner02");
        result.put("template", template);
        List<HyOrderDetail> list = getOrderDetailsListByOrderId(orderIds);
        List<EntityMap> dataList = new ArrayList<>();
        for (HyOrderDetail orderDetail : list) {
            String orderId = orderDetail.getOrderId();
            HyOrder order = hyOrderService.getById(orderId);
            BigDecimal drugJs = orderDetail.getPrintDrugJs();
            EntityMap map = new EntityMap();
            Long customId = order.getCustomId();
            Long companyId = order.getCompanyId();
            BusCustom custom = customService.getById(customId);
            map.put("orderDetailsId", orderDetail.getOrderDetailsId());
            SysCompany company = companyService.getById(companyId);
            //发货地址
            map.put("companyAddress", company.getCompanyAddress());
            //发货方
            map.put("companyName", company.getCompanyShortName());
            //客户名称
            map.put("customName", custom.getCustomName());
            //商品名称
            map.put("drugsName", orderDetail.getDrugsName());
            //件数
            map.put("drugJs", drugJs.setScale(2, BigDecimal.ROUND_HALF_UP));
            Integer drugJsCount = drugJs.setScale(0, BigDecimal.ROUND_UP).intValue();
            //单品件数
            map.put("drugJsCount", drugJsCount);
            //总件数
            BigDecimal totalDrugJs = countDrugJs(orderIds);
            map.put("totalDrugJs", drugJsCount + "/" + totalDrugJs.setScale(0, BigDecimal.ROUND_UP).intValue());
            //出库日期
            map.put("outDate", DateUtils.getNowDate());
            //打印日期
            map.put("printDate", DateUtils.getNowDate());

            //收货人电话
            map.put("customUserTel", order.getCustomUserTel());
            //收货人地址
            map.put("customAddress", order.getCustomAddress());
            //收货人
            map.put("customUserName", order.getCustomUserName());
            //订单编号
            map.put("outOrderNo", order.getOutOrderNo());
            map.put("barcode", "CKA" + order.getOutOrderNo());
            Long userId = OpenHelper.getUserId();
            BaseUser baseUser = baseUserService.getById(userId);
            //发货人电话
            map.put("mobile", baseUser.getMobile());
            //发货人
            map.put("outNickName", OpenHelper.getNickName());
            dataList.add(map);
        }
        result.put("dataList", dataList);
        return ResultBody.ok(result);
    }

    /**
     * 获取订单打印信息
     *
     * @param orderId
     * @return
     */
    @Override
    public ResultBody getOutOrderPrint2(String orderId) {
        EntityMap result = new EntityMap();
        String template = sysPrintDesignerService.getContentByDesignCode("PrintDesigner02");
        result.put("template", template);
        List<HyOrder> list = hyOrderService.getOrderList(orderId);
        List<EntityMap> datas = new ArrayList<>();
        for (HyOrder order : list) {
            EntityMap map = new EntityMap();
            Long companyId = order.getCompanyId();
            Long customId = order.getCustomId();
            BusCustom custom = customService.getById(customId);
            map.put("orderId", order.getOrderId());
            map.put("outOrderNo", order.getOutOrderNo());
            map.put("barcode", "CKA" + order.getOutOrderNo());
            map.put("remark", "厂检,出库单");
            //客户名称
            map.put("customName", custom.getCustomName());
            Long userId = OpenHelper.getUserId();
            BaseUser baseUser = userService.getById(userId);
            SysCompany company = companyService.getById(companyId);
            //发货地址
            map.put("companyAddress", company.getCompanyAddress());
            //发货方
            map.put("companyName", company.getCompanyShortName());
            List<String> drugsName = getDrugsNames(order.getOrderId());
            BigDecimal drugJs = countDrugJs(order.getOrderId());
            if (FlymeUtils.isNotEmpty(drugsName)) {
                if (drugsName.size() == 1) {
                    //商品名称
                    map.put("drugsName", drugsName.get(0));
                } else {
                    map.put("drugsName", drugsName.get(0) + "...");
                }
            }
            //件数
            map.put("drugJs", drugJs);
            //整件数
            map.put("drugJsCount", drugJs.setScale(0, BigDecimal.ROUND_UP));
            map.put("totalDrugJs", drugJs.setScale(0, BigDecimal.ROUND_UP));
            //出库日期
            map.put("outDate", DateUtils.getNowDate());
            //打印日期
            map.put("printDate", DateUtils.getNowDate());
            //发货人
            map.put("outNickName", OpenHelper.getNickName());
            //发货人电话
            map.put("mobile", baseUser.getMobile());

            //收货人电话
            map.put("customUserTel", order.getCustomUserTel());
            //收货人地址
            map.put("customAddress", order.getCustomAddress());
            //收货人
            map.put("customUserName", order.getCustomUserName());
            datas.add(map);
        }
        result.put("dataList", datas);
        return ResultBody.ok(result);
    }

    @Override
    public Boolean customUpdate(HyOrderDetail hyOrderDetail) {
        String orderDetailsId = hyOrderDetail.getOrderDetailsId();
        HyOrderDetail orderDetail = getById(orderDetailsId);
        BeanUtil.copyProperties(hyOrderDetail, orderDetail, CopyOptions.create().ignoreNullValue());
        return updateById(orderDetail);
    }

    @Override
    public BigDecimal totalCustomBondAmount(Long saleManId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery<>(HyOrderDetail.class);
        cq.select("sum(customBond)");
        cq.isNotNull("saleManBalanceId");
        cq.eq("customReturnState", CommonConstants.INT_0);
        cq.eq(true, "saleManId", saleManId);
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        if (FlymeUtils.isEmpty(amount)) {
            amount = new BigDecimal("0");
        }
        return amount;
    }

    @Override
    public BigDecimal totalCustomBondAmount(Long saleManId, Long companyId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery<>(HyOrderDetail.class);
        cq.select("sum(customBond)");
        cq.eq("customReturnState", CommonConstants.INT_0);
        cq.eq(true, "saleManId", saleManId);
        cq.eq(true, "companyId", companyId);
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        if (FlymeUtils.isEmpty(amount)) {
            amount = new BigDecimal("0");
        }
        return amount;
    }

    public BigDecimal totalCustomBondAmount(Long saleManId, Long companyId, String orderId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery<>(HyOrderDetail.class);
        cq.select("sum(customBond)");
        cq.eq("customReturnState", CommonConstants.INT_0);
        cq.ne(true, "orderId", orderId);
        cq.eq(true, "saleManId", saleManId);
        cq.eq(true, "companyId", companyId);
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        if (FlymeUtils.isEmpty(amount)) {
            amount = new BigDecimal("0");
        }
        return amount;
    }


    @Override
    public String selectLastOrderDetailsId(Long companyId, String hostName) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "orderDetailsId");
        cq.eq(true, "companyId", companyId);
        cq.eq(true, "hostName", hostName);
        cq.orderByDesc("createTime", "orderDetailsId");
        cq.limit(1);
        return getObj(cq, e -> e.toString());
    }

    @Override
    public Integer countCdCount(String drugNo, String drugLotNo, String storeCode, Integer orderState,BigDecimal costPrice) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("sum(saleNum) saleNum");
        cq.eq(true, "ho.syncTag", 0);
        //未提单
        cq.eq(true, "ho.sendState", 0);
        cq.eq(true, "ho.companyId", OpenHelper.getCompanyId());
        cq.eq(true, "drugNo", drugNo);
        if(FlymeUtils.isNotEmpty(costPrice)) {
            cq.eq(true, "costPrice", costPrice);
        }
        cq.eq(FlymeUtils.isNotEmpty(drugLotNo), "drugLotNo", drugLotNo);
        cq.eq(FlymeUtils.isNotEmpty(storeCode), "storeCode", storeCode);
        cq.createJoin(HyOrder.class);
        EntityMap map = findOne(cq);
        if (FlymeUtils.isNotEmpty(map)) {
            BigDecimal count = map.getBigDecimal("saleNum");
            return count.intValue();
        }
        return 0;
    }

    @Override
    public List<String> getDrugsNames(String orderId) {
        List<String> drugNameList = new ArrayList<>();
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("DISTINCT drugsName");
        cq.in(true, "orderId", orderId.split(","));
        List<EntityMap> list = selectEntityMap(cq);
        if (FlymeUtils.isNotEmpty(list)) {
            for (EntityMap entityMap : list) {
                String drugName = entityMap.get("drugsName");
                drugNameList.add(drugName);
            }
        }
        return drugNameList;
    }

    @Override
    public List<String> getOrderDetails(String orderId) {
        List<String> ids = new ArrayList<>();
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("orderDetailsId");
        cq.eq(true, "orderId", orderId);
        List<EntityMap> list = selectEntityMap(cq);
        if (FlymeUtils.isNotEmpty(list)) {
            for (EntityMap entityMap : list) {
                String orderDetailsId = entityMap.get("orderDetailsId");
                ids.add(orderDetailsId);
            }
        }
        return ids;
    }

    @Override
    public BigDecimal countDrugJs(String orderId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("sum(printDrugJs) drugJs");
        cq.in(true, "orderId", orderId.split(","));
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        if (FlymeUtils.isEmpty(amount)) {
            amount = new BigDecimal("0");
        }
        return amount;
    }

    @Override
    public EntityMap selectOrderDetailsInfo(String orderDetailsId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select(HyOrderDetail.class, "orderDetailsId", "orderId", "parentId", "drugLotNo", "drugNo", "drugsName", "drugsSpec", "sendDate", "saleNum", "salePrice", "saleAmount", "costPrice", "costAmount", "storeCode", "drugJs", "printDrugJs", "generationDate", "expirationDate", "reason");
        cq.eq(true, "orderDetailsId", orderDetailsId);
        return findOne(cq);
    }


    @Override
    public Boolean updatePrintDrugJs(String orderDetailsId, BigDecimal printDrugJs) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "printDrugJs", printDrugJs);
        cu.eq(true, "orderDetailsId", orderDetailsId);
        update(cu);
        return true;
    }

    private List<HyOrderDetail> getOrderDetailsList(String orderDetailsId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("orderDetailsId", "orderId", "drugLotNo", "drugsName", "drugsSpec", "sendDate", "saleNum", "storeName", "drugJs", "printDrugJs", "generationDate", "expirationDate");
        cq.in(true, "orderDetailsId", orderDetailsId.split(","));
        return list(cq);
    }

    private List<HyOrderDetail> getOrderDetailsListByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrderDetail.class);
        cq.select("orderDetailsId", "orderId", "drugLotNo", "drugsName", "drugsSpec", "sendDate", "saleNum", "storeName", "drugJs", "printDrugJs", "generationDate", "expirationDate");
        cq.in(true, "orderId", orderId.split(","));
        return list(cq);
    }

}
